package com.jeesite.modules.topiam.oauth;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.config.Global;
import com.xkcoding.http.support.HttpHeader;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TopIAM 认证请求
 *
 * @author SanLi
 * Created by support@topiam.cn on  2023/8/29
 */
public class AuthTopIamRequest extends AuthDefaultRequest {
    private final Logger logger = LoggerFactory.getLogger(AuthTopIamRequest.class);

    public static final String BASE_HOST = Global.getProperty("oauth2.topiam.serverUrl");

    public static final AuthSource TOPIAM = new AuthSource() {
        /**
         * 授权的api
         *
         * @return url
         */
        @Override
        public String authorize() {
            return AuthTopIamRequest.BASE_HOST + "/oauth2/auth";
        }

        /**
         * 获取accessToken的api
         *
         * @return url
         */
        @Override
        public String accessToken() {
            return AuthTopIamRequest.BASE_HOST + "/oauth2/token";
        }

        /**
         * 获取用户信息的api
         *
         * @return url
         */
        @Override
        public String userInfo() {
            return AuthTopIamRequest.BASE_HOST + "/oauth2/userinfo";
        }

        /**
         * 平台对应的 AuthRequest 实现类，必须继承自 {@link AuthDefaultRequest}
         *
         * @return class
         */
        @Override
        public Class<? extends AuthDefaultRequest> getTargetClass() {
            return AuthTopIamRequest.class;
        }
    };


    public AuthTopIamRequest(AuthConfig config) {
        super(config, TOPIAM);
    }

    public AuthTopIamRequest(AuthConfig config, AuthSource source) {
        super(config, source);
    }

    public AuthTopIamRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, TOPIAM, authStateCache);
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        logger.debug("Get TopIAM access_token request :{}", JSONObject.toJSONString(authCallback));
        String body = doPostAuthorizationCode(authCallback.getCode());
        JSONObject response = JSONObject.parseObject(body);
        logger.debug("Get TopIAM access_token response :{}", JSONObject.toJSONString(response));
        checkResponse(response);
        //@formatter:off
        return AuthToken.builder()
                .accessToken(response.getString("access_token"))
                .refreshToken(response.getString("refresh_token"))
                .idToken(response.getString("id_token"))
                .tokenType(response.getString("token_type"))
                .scope(response.getString("scope"))
                .build();
        //@formatter:on
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        logger.debug("Get TopIAM user info request :{}", JSONObject.toJSONString(authToken));
        String body = doGetUserInfo(authToken);
        JSONObject result = JSONObject.parseObject(body);
        logger.debug("Get TopIAM user info response :{}", JSONObject.toJSONString(authToken));
        checkResponse(result);
        //@formatter:off
        return AuthUser.builder()
                .uuid(result.getString("sub"))
                .username(result.getString("preferred_username"))
                .nickname(result.getString("nickname"))
                .avatar(result.getString("picture"))
                .email(result.getString("email"))
                .token(authToken)
                .source(source.toString())
                .build();
        //@formatter:on
    }


    @Override
    protected String doGetUserInfo(AuthToken authToken) {
        return new HttpUtils(config.getHttpConfig()).get(source.userInfo(), null, new HttpHeader()
                .add("Content-Type", "application/json")
                .add("Authorization", "Bearer " + authToken.getAccessToken()), false).getBody();
    }


    @Override
    public String authorize(String state) {
        return UrlBuilder.fromBaseUrl(super.authorize(state))
                .queryParam("scope", StringUtils.join(this.config.getScopes(), " "))
                .build();
    }

    public static void checkResponse(JSONObject object) {
        // oauth/token 验证异常
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("error_description"));
        }
        // user 验证异常
        if (object.containsKey("message")) {
            throw new AuthException(object.getString("message"));
        }
    }

}
